/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.property.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import me.zhengjie.modules.property.domain.Repay;
import me.zhengjie.modules.summary.repository.RecordSubRepository;
import me.zhengjie.modules.utils.DownExcelTemp;
import me.zhengjie.modules.utils.DownLoadUtil;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.property.repository.RepayRepository;
import me.zhengjie.modules.property.service.RepayService;
import me.zhengjie.modules.property.service.dto.RepayDto;
import me.zhengjie.modules.property.service.dto.RepayQueryCriteria;
import me.zhengjie.modules.property.service.mapstruct.RepayMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2023-04-21
**/
@Service
@RequiredArgsConstructor
public class RepayServiceImpl implements RepayService {

    private final RepayRepository repayRepository;
    private final RepayMapper repayMapper;

    @Resource
    private RecordSubRepository recordSubRepository;

    private static String warningInfo = "带*号的列请选择下拉框内的数据，红色字体为必填项";

    @Override
    public Map<String,Object> queryAll(RepayQueryCriteria criteria, Pageable pageable){
        Page<Repay> page = repayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(repayMapper::toDto));
    }

    @Override
    public List<RepayDto> queryAll(RepayQueryCriteria criteria){
        return repayMapper.toDto(repayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public RepayDto findById(String id) {
        Repay repay = repayRepository.findById(id).orElseGet(Repay::new);
        ValidationUtil.isNull(repay.getId(),"Repay","id",id);
        return repayMapper.toDto(repay);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RepayDto create(Repay resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return repayMapper.toDto(repayRepository.save(resources));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Repay resources) {
        Repay repay = repayRepository.findById(resources.getId()).orElseGet(Repay::new);
        ValidationUtil.isNull( repay.getId(),"Repay","id",resources.getId());
        repay.copy(resources);
        repayRepository.save(repay);

        recordSubRepository.updateSumNumber(repayRepository.hasRepay(),"已还本金利息:"+repayRepository.hasRepay()+"元,未还本金"+repayRepository.noRepay()+"元","60万");
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            repayRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RepayDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RepayDto repay : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("还款类型", repay.getRepayType());
            map.put("还款期号", repay.getRepayIssue());
            map.put("还款日期", repay.getRepayDate());
            map.put("还款总额", repay.getRepayPrice());
            map.put("还款本金", repay.getRepayPrincipal());
            map.put("还款利息", repay.getRepayInterest());
            map.put("状态", repay.getRepayStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void exportTemplate(HttpServletResponse response) throws IOException {
        //将虚拟路径转换物理路径
        String newFilePath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
        //模板名称
        String fileName = "等额本息模板";
        //设置头
        String[] headers = {"还款期号", "还款日期", "还款总额", "还款本金", "还款利息", "状态"};
        Integer[] mandatory = {0, 1, 2, 3, 4, 5};
        List<String> headerList = new ArrayList<>();
        for (int i = 0; i < headers.length; i++) {
            headerList.add(headers[i]);
        }
        //存放数据集
        List<List<String>> downData = new ArrayList<>();
        //数据所在列
        List<String> downRows = Lists.newArrayList();
        downRows.add("0");
        downRows.add("2");
        downRows.add("3");
        //生成待下载excel模板
        DownExcelTemp.createExcelTemplate(newFilePath, fileName, headerList, downData, downRows, mandatory, warningInfo);
        //下载模板
        DownLoadUtil.downFile(newFilePath, fileName, response);
        //删除临时文件
        File delFile = new File(newFilePath);
        if (delFile.exists()) {
            delFile.delete();
        }
    }

    @Override
    public Map<String,Object> upload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            ExcelReader reader;
            reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("还款期号", "repayIssue");
            reader.addHeaderAlias("还款日期", "repayDate");
            reader.addHeaderAlias("还款总额", "repayPrice");
            reader.addHeaderAlias("还款本金", "repayPrincipal");
            reader.addHeaderAlias("还款利息", "repayInterest");
            reader.addHeaderAlias("状态", "repayStatus");

            List<Repay> list = reader.readAll(Repay.class);
            List<Repay> result = new ArrayList<>();
            list.remove(0);

            for (Repay repay : list) {
                repay.setId(IdUtil.simpleUUID());
                repay.setRepayType("1");
                result.add(repay);
            }
            repayRepository.saveAll(result);
            map.put("state", "success");
            map.put("info", "导入" + list.size() + "条数据，成功" + result.size() + "条");

        } catch (IOException e) {
            map.put("state", "error");
            map.put("message", "导入失败");
        }
        return map;
    }

    @Override
    public Map<String, Double> countTotalNum() {
        return repayRepository.countTotalNum();
    }





}